/**筛选*/
// 数据处理：按状态过滤
function filterNodesByLevel(level,nodes){
    var sel_nodes = [];
    nodes.forEach(function (node) {
        if(node.layout.level <= level){
            sel_nodes.push(node);
        }
    })
    return sel_nodes;
}
// 数据处理：按状态过滤
function filterNodesByStatus(status,nodes){
    if(status == 'all'){
        return nodes;
    }

    var sel_nodes = [];
    for(var i = 0; i < nodes.length; i++){
        var node = nodes[i];
        if((node.data.obj.labels == 'Company' && node.data.obj.properties.status == status) || node.nodeId == _rootNode.nodeId){
            sel_nodes.push(node);
        }
    }
    return sel_nodes;
}
// 数据处理：按持股数过滤
function filterNodesByStockNum(num,links){
    var sel_links = [];
    for(var i = 0; i < links.length; i++){
        if(num == links[i].data.obj.properties.stockPercent){
            sel_links.push(links[i]);
        }
    }
    return sel_links;
}
// 数据处理：按投资过滤
function filterNodesByInvest(invest,nodes,links){
    /*获取直接投资的节点*/
    function getInvestNodes(nodeId,links) {
        var investNodes = [];
        for(var i = 0; i < links.length; i++){
            var link = links[i];
            if(link.sourceNode.nodeId == nodeId && link.data.obj.type == 'INVEST'){
                investNodes.push(link.targetNode);
            }
        }

        //investNodes = uniqeByKeys(investNodes,['nodeId']);
        return investNodes;
    }
    /*获取公司股东*/
    function getCompanyStockholder(nodeId,links) {
        var stockholderNodes = [];
        for(var i = 0; i < links.length; i++){
            var link = links[i];
            if(link.targetNode.nodeId == nodeId && link.data.obj.type == 'INVEST'){
                stockholderNodes.push(link.sourceNode);
            }
        }

        //stockholderNodes = uniqeByKeys(stockholderNodes,['nodeId']);
        return stockholderNodes;
    }
    /*获取董监高法*/
    function getPersonStockholder(nodeId,links) {
        var stockholderNodes = [];
        for(var i = 0; i < links.length; i++){
            var link = links[i];
            if(link.targetNode.nodeId == nodeId && link.data.obj.type == 'INVEST' && link.sourceNode.data.obj.labels[0] == 'Person'){
                stockholderNodes.push(link.sourceNode);
            }
        }

        //stockholderNodes = uniqeByKeys(stockholderNodes,['nodeId']);
        return stockholderNodes;
    }

    var sel_nodes = [];

    switch (invest){
        case 'all':
            return nodes;
            break;
        case 'direct': //直接投资
            sel_nodes = getInvestNodes(_rootNode.nodeId,links);
            break;
        case 'stockholder': // 股东投资
            var nextNodes = [];
            var stockholderNodes = getCompanyStockholder(_rootNode.nodeId,links);
            for(var i = 0; i < stockholderNodes.length; i++){
                nextNodes = nextNodes.concat(getInvestNodes(stockholderNodes[i].nodeId,links));
            }
            sel_nodes = stockholderNodes.concat(nextNodes);
            break;
        case 'legal': // 董监高法投资
            var nextNodes = [];
            var stockholderNodes = getPersonStockholder(_rootNode.nodeId,links);
            for(var i = 0; i < stockholderNodes.length; i++){
                nextNodes = nextNodes.concat(getInvestNodes(stockholderNodes[i].nodeId,links));
            }
            sel_nodes = stockholderNodes.concat(nextNodes);
            break;
    }


    sel_nodes = sel_nodes.concat(_rootNode);
    sel_nodes = uniqeByKeys(sel_nodes,['nodeId']);
    return sel_nodes;
}
// 数据处理：根据所有条件过滤
function filter(rootData){
    function isParentExist(node,nodes,links) {
        var isExist = false;
        var parentLevel = node.layout.level - 1;

        if(parentLevel < 2){
            return true;
        }

        for(var i = 0; i < links.length; i++){
            var link = links[i];
            if((link.sourceNode.nodeId == node.nodeId && link.targetNode.layout.level == parentLevel) && isNodeExist(link.targetNode.nodeId,nodes) ){
                isExist = true;
                break;
            }
            if((link.targetNode.nodeId == node.nodeId && link.sourceNode.layout.level == parentLevel) && isNodeExist(link.sourceNode.nodeId,nodes) ){
                isExist = true;
                break;
            }
        }

        return isExist;
    }
    function getFilterData(rootData) {
        //
        var sel_nodes = [];
        for(var i = 0; i < rootData.nodes.length; i++){
            sel_nodes.push(rootData.nodes[i]);
        }
        var sel_links = [];
        for(var i = 0; i < rootData.links.length; i++){
            sel_links.push(rootData.links[i]);
        }

        var level = $('#SelPanel').attr('param-level');
        var status = $('#SelPanel').attr('param-status');
        var num = $('#SelPanel').attr('param-num');
        var invest = $('#SelPanel').attr('param-invest');

        //console.log('status:' + status + ' num:' + num + ' invest:' + invest);

        // 层级
        level = parseInt(level) + 1;
        sel_nodes = filterNodesByLevel(level,sel_nodes);

        // 状态
        if(status){
            sel_nodes = filterNodesByStatus(status,sel_nodes);
        }

        // 持股
        var stock_nodes = [];
        if(num && num != 0){
            sel_links = filterLinksByNodes(sel_nodes,sel_links);
            sel_links = filterNodesByStockNum(num,sel_links);
            for(var i = 0; i < sel_links.length;i++){
                stock_nodes.push(sel_links[i].sourceNode);
                stock_nodes.push(sel_links[i].targetNode);
            }
            sel_nodes = uniqeByKeys(stock_nodes,['nodeId']);
        }

        // 投资
        if(invest){
            sel_nodes = filterNodesByInvest(invest,sel_nodes,sel_links);
        }

        //父节点不存在则删除
        var sel_nodes2 = [];
        sel_nodes.forEach(function (node,i) {
            if(isParentExist(node,sel_nodes,sel_links)){
                sel_nodes2.push(node);
            }
        })
        sel_links = filterLinksByNodes(sel_nodes2,sel_links);

        return {links:sel_links,nodes:sel_nodes2};
    }

    var nodesIds = [];
    var selGraph= getFilterData(rootData)
    selGraph.nodes.forEach(function (node) {
        nodesIds.push(node.nodeId);
    })
    highLightFilter(nodesIds,cy);

    /*//
    //$("#load_data").show();

    // 保证始终存在当前节点
    /!*if(sel_nodes2.length == 0){
        sel_nodes2.push(_rootNode);
    }*!/

    // 更新图谱
    /!*$("#TrTxt").removeClass('active');
    domUpdate(getFilterData(rootData));*!/

    /!*setTimeout(function () {
        domUpdate({links:sel_links,nodes:sel_nodes2});
    },5000)*!/;*/
}
//
function filterReset(){
    $('#SelPanel').attr('param-level','2');
    $('#SelPanel').attr('param-status','');
    $('#SelPanel').attr('param-num','');
    $('#SelPanel').attr('param-invest','');

    $('#ShowLevel a').removeClass('active');
    $('#ShowLevel a').eq(1).addClass('active');
    $('#ShowStatus a').removeClass('active');
    $('#ShowStatus a').eq(0).addClass('active');
    $('#ShowInvest a').removeClass('active');
    $('#ShowInvest a').eq(0).addClass('active');
    $('#inputRange').val(0);
    $('#inputRange').css({'backgroundSize':'0% 100%'});
}




//截图2
function downImg(imgdata){
    var type = 'png';
    //将mime-type改为image/octet-stream,强制让浏览器下载
    var fixtype = function (type) {
        type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
        var r = type.match(/png|jpeg|bmp|gif/)[0];
        return 'image/' + r;
    }
    imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')
    //将图片保存到本地
    var saveFile = function (data, filename) {
        var link = document.createElement('a');
        link.href = data;
        link.download = filename;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        link.dispatchEvent(event);
    }
    var filename = new Date().toLocaleDateString() + '.' + type;
    saveFile(imgdata, filename);
}
//截图2 IE
// function downloadimgIE(canvas) {
//     function post(URL, PARAMS) {
//         var temp = document.createElement("form");
//         temp.action = URL;
//         temp.enctype = "multipart/form-data";
//         temp.method = "post";
//         temp.style.display = "none";
//         for (var x in PARAMS) {
//             var opt = document.createElement("textarea");
//             opt.name = x;
//             opt.value = PARAMS[x];
//             temp.appendChild(opt);
//         }
//         document.body.appendChild(temp);
//         temp.submit();
//         return temp;
//     }

//     var qual = 1;
//     if(canvas.width>3000){
//         qual = 0.5;
//     }else if(canvas.width>5000){
//         qual = 0.4;
//     }
//     //设置保存图片的类型
//     var imgdata = canvas.toDataURL('image/jpeg',qual);
//     //var filename = '{{$smarty.get.name}}的关联图谱_'+new Date().toLocaleDateString() + '.jpeg';
//     // var filename = _FILENAME + '的关联图谱.png';
//     var filename = '企查查_图谱.png';
//     post(INDEX_URL+'cms_downloadimg?filename='+filename, {img:imgdata});
// }
//截图1
function canvasImg(imgData){
    var img = new Image();

    img.onload = function(e){

        var canvas = document.createElement('canvas');  //准备空画布
        canvas.width = img.width;
        canvas.height = img.height;
        var context = canvas.getContext('2d');  //取得画布的2d绘图上下文
        context.fillStyle = "#fff";
        context.fillRect(0,0,canvas.width,canvas.height);

        //画水印
        // var shuiying = new Image();
        // shuiying.src="/material/theme/chacha/cms/v2/images/shuiying2.png";
        // if(canvas.width>320){
        //     context.drawImage(shuiying, canvas.width/2-160, canvas.height/2-80,320,160);
        // }else{
        //     context.drawImage(shuiying, canvas.width/2-80, canvas.height/2-40,160,80);
        // }

        var shuiying = new Image();
        //shuiying.src="/material/theme/chacha/cms/v2/images/shuiying2.png";
        for(var i=0;i < canvas.width+100; i+=600){
            for(var j=0; j< canvas.height+100; j+=456){
                context.drawImage(shuiying, i, j);
            }
        }

        //画图谱
        context.drawImage(img, 0, 0);

        if(canvas.width>400){
            var marker = '关系图谱由xx基于公开信息利用大数据分析引擎独家生成';
            context.font = "28px 微软雅黑";
            context.fillStyle = "#aaaaaa";
            context.fillText(marker, canvas.width/2-context.measureText(marker).width/2, canvas.height-30);
        }
		
		downImg(canvas.toDataURL('image/jpeg',1));
        //downloadimgIE(canvas);

        /*if(!!window.ActiveXObject || "ActiveXObject" in window){ // ie
            context.drawImage(shuiying, canvas.width/2-160, canvas.height/2-80,320,160);
            downloadimgIE(canvas);
        } else {
            downImg(canvas.toDataURL('image/jpeg',1));
        }*/
    }

    img.src = imgData;
}


function refresh(keyNo) {
    $('.company-detail').fadeOut();
    $('#MainCy').html('');

    $('#TrTxt').removeClass('active');
    getData();
    focusCancel();
    filterReset();

    //页面
    try{
        hideSearchBoxHide();
    }catch (e){}
}



/**详情弹窗*/
function showPerTupu(type){
    var canshow = $("#ShowPerTupu").attr('canshow');
    if(canshow){
        var keyNo = $("#ShowPerTupu").attr('keyno');
        refresh(keyNo);
    }
}
/*关闭详情*/
function popclose(dom){
    $(dom).parent().parent().fadeOut();
}
/*人物头像没有时处理*/
function personImgErr() {
    var name = $(".ea_name").text();
    $('#face_oss').hide();
    $('.ea_defaultImg').show();
    $('.ea_defaultImg').text(name[0]);
}
/**END 详情弹窗*/


function isFullScreen(){
    if(document.fullscreen){
        return true;
    }else if(document.mozFullScreen){
        return true;
    }else if(document.webkitIsFullScreen){
        return true;
    }else if(document.msFullscreenElement){
        return true;
    }else{
        return false;
    }
}
function launchFullScreen(element) {
    if(element.requestFullscreen) {
        element.requestFullscreen();
    }else if(element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    }else if(element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if(element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}
function exitFullScreen(){
    if(document.exitFullscreen){
        document.exitFullscreen();
    }
    else if(document.mozCancelFullScreen){
        document.mozCancelFullScreen();
    }
    else if(document.msExitFullscreen){
        document.msExitFullscreen();
    }
    else if(document.webkitCancelFullScreen){
        document.webkitCancelFullScreen();
    }
}


function fullScreen() {
	var old = cy.pan();
	var distance = 60;
	if(isFullScreen()){
		cy.pan({
			x:old.x,
			y:old.y - distance
		});
		exitFullScreen();
		$("#fullScreenText").text("全屏");
		$("#fullScreenicon").removeClass("fa-arrows");
		$("#fullScreenicon").addClass("fa-arrows-alt");
	} else {
		cy.pan({
			x:old.x,
			y:old.y + distance
		});
		launchFullScreen($('#Main')[0]);
		$("#fullScreenText").text("退出");
		$("#fullScreenicon").removeClass("fa-arrows-alt");
		$("#fullScreenicon").addClass("fa-arrows");
	}
}
	

function toggleText() {
    if($("#LiFont").hasClass('active')){
        $("#LiFont").removeClass('active');
        cy.collection("edge").removeClass("edgeShowText");
        cy.collection("edge").addClass("edgeHideText");
    } else {
        $("#LiFont").addClass('active');
		cy.collection("edge").removeClass("edgeHideText");
        cy.collection("edge").addClass("edgeShowText");
    }
}

function scale(type) {
    var rate = 0.2;
    var scale = cy.zoom();
    if(type==1){
        scale += rate;
    }else if(type==2){
        scale -= rate;
    }
    cy.zoom({
        level: scale, // the zoom level
    });
}